<template>
  <Teleport to="body">
    <Transition name="fade">
      <div v-if="open" class="fixed inset-0 z-[9998]">
        <!-- 背景遮罩：点击关闭抽屉 -->
        <div class="absolute inset-0 bg-black/50" @click="close"></div>
        <!-- 右侧抽屉面板 -->
        <Transition name="slide">
          <aside class="absolute right-0 top-0 bottom-0 w-[92vw] max-w-md bg-neutral-900/95 backdrop-blur-md border-l border-white/10 text-white p-5 flex flex-col" v-if="open">
            <!-- 头部：标题 + 关闭按钮 -->
            <header class="flex items-center justify-between mb-4">
              <h3 class="text-lg font-semibold">购物车</h3>
              <button class="text-white/60 hover:text-white" @click="close">×</button>
            </header>
            <!-- 列表区域：商品行 -->
            <div class="flex-1 overflow-auto space-y-3 pr-1">
              <div v-if="items.length === 0" class="text-white/60 text-sm py-10 text-center">购物车是空的</div>
              <div v-for="it in items" :key="it.id" class="flex gap-3 items-center card-minimal p-3">
                <!-- 方形缩略图容器：保持一致画幅，避免行高跳动 -->
                <div class="relative w-16 shrink-0">
                  <div class="pt-[100%]"></div>
                  <img :src="it.cover || '/images/apple.svg'" :alt="it.name"
                       class="absolute inset-0 w-full h-full object-cover rounded-lg border border-white/10"
                       loading="lazy" decoding="async" referrerpolicy="no-referrer" draggable="false"
                       @error="(e)=> e.target.src = '/images/apple.svg'" />
                </div>
                <div class="flex-1 min-w-0">
                  <div class="truncate font-medium">{{ it.name }}</div>
                  <div class="text-emerald-400 font-bold">￥{{ it.price }}</div>
                  <!-- 数量操作：最小 1 -->
                  <div class="mt-1 inline-flex items-center gap-2">
                    <button class="px-2 rounded-full border border-white/15" @click="decrease(it)">-</button>
                    <input type="number" class="w-14 text-center input-control px-2 py-1" v-model.number="it.qty" min="1" @change="update(it)" />
                    <button class="px-2 rounded-full border border-white/15" @click="increase(it)">+</button>
                  </div>
                </div>
                <button class="text-white/50 hover:text-red-400" @click="removeItem(it)">删除</button>
              </div>
            </div>
            <!-- 底部合计与操作按钮 -->
            <footer class="pt-3 border-t border-white/10 space-y-3">
              <div class="flex items-center justify-between">
                <span class="text-white/60">合计</span>
                <span class="text-xl font-bold text-emerald-400">￥{{ total }}</span>
              </div>
              <div class="flex gap-2">
                <button class="btn-outline flex-1" @click="clearAll" :disabled="items.length===0">清空</button>
                <button class="btn-primary flex-1" @click="goCheckout">去结算</button>
              </div>
            </footer>
          </aside>
        </Transition>
      </div>
    </Transition>
  </Teleport>
</template>

<script>
// 使用 Vue2 风格（Options API）：data / computed / watch / methods
import toast from '../composables/toast'
import { createOrder } from '@/api/orderApi.js'
import { useAuthStore } from '../stores/auth'

export default {
  name: 'CartDrawer',
  // 组件对外暴露的属性（与 v-model:open 对应）
  props: {
    open: { type: Boolean, default: false }
  },
  // 声明会触发的事件，便于类型提示（Vue3 下可选）
  emits: ['update:open'],
  data(){
    return {
      // 购物车条目列表：[{ id, name, price, cover, qty }]
      items: []
    }
  },
  computed: {
    // 计算属性：合计金额（两位小数展示）
    total(){
      return this.items.reduce((s, x) => s + x.price * x.qty, 0).toFixed(2)
    }
  },
  watch: {
    // 打开抽屉时，重新从本地存储读取，确保与其它页面/组件同步
    open(val){ if (val) this.load() }
  },
  mounted(){
    // 监听全局自定义事件：当其它模块更新购物车后，抽屟自动刷新
    window.addEventListener('cart-updated', this.load)
  },
  beforeUnmount(){
    window.removeEventListener('cart-updated', this.load)
  },
  methods: {
    // 关闭抽屉：向父组件派发 v-model 更新
    close(){ this.$emit('update:open', false) },
    // 从本地读取购物车
    load(){
      try{
        const raw = JSON.parse(localStorage.getItem('cart') || '[]')
        this.items = (Array.isArray(raw) ? raw : []).map(it => ({
          id: it.id,
          name: it.name,
          price: Number(it.price) || 0,
          cover: it.cover,
          qty: it.qty
        }))
      }catch(_){ this.items = [] }
    },
    // 写回与广播
    persist(){
      localStorage.setItem('cart', JSON.stringify(this.items))
      window.dispatchEvent(new CustomEvent('cart-updated'))
    },
    // 数量 +1（索引版本，兼容旧模板）
    inc(i){ this.items[i].qty++; this.persist() },
    // 数量 -1（下限 1，索引版本）
    dec(i){ this.items[i].qty = Math.max(1, this.items[i].qty - 1); this.persist() },
    // 删除（索引版本）
    remove(i){ this.items.splice(i, 1); this.persist() },
    // 清空全部条目
    clearAll(){
      if(this.items.length === 0) return
      this.items = []
      this.persist()
      toast.info('已清空购物车')
    },
    // —— 以下为对象版本，匹配当前模板事件 ——
    increase(item){
      const idx = this.items.findIndex(x => String(x.id) === String(item.id))
      if(idx > -1){ this.items[idx].qty++; this.persist() }
    },
    decrease(item){
      const idx = this.items.findIndex(x => String(x.id) === String(item.id))
      if(idx > -1){
        const cur = Number(this.items[idx].qty) || 1
        this.items[idx].qty = Math.max(1, cur - 1)
        this.persist()
      }
    },
    update(item){
      const idx = this.items.findIndex(x => String(x.id) === String(item.id))
      if(idx > -1){
        const v = parseInt(this.items[idx].qty, 10)
        this.items[idx].qty = Number.isFinite(v) && v > 0 ? v : 1
        this.persist()
      }
    },
    removeItem(item){
      const idx = this.items.findIndex(x => String(x.id) === String(item.id))
      if(idx > -1){
        this.items.splice(idx, 1)
        this.persist()
        toast.info('已删除该商品')
      }
    },
    // 预创建订单并跳转
    async goCheckout(){
      const auth = useAuthStore()
      if(!auth.user?.id){ toast.error('请先登录'); return }
      if(this.items.length===0){ toast.error('购物车为空'); return }
      // 不在购物车抽屉预下单，直接进入结算页，由结算页在支付前创建/校验订单号
      this.close()
      this.$router.push('/checkout')
    }
  }
}
</script>

<style scoped>
.fade-enter-from,.fade-leave-to{ opacity:0 }
.fade-enter-active,.fade-leave-active{ transition: opacity .2s ease }
.slide-enter-from{ transform: translateX(100%); }
.slide-enter-active{ transition: transform .25s cubic-bezier(.22,1,.36,1); }
.slide-leave-to{ transform: translateX(100%); }
.slide-leave-active{ transition: transform .2s ease; }
</style>